package com.hnevc.broadcastdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private MyBroadCastReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonClick(View view) {
        Log.e(TAG, "buttonClick: " );
        //获取触发点击事件的控件id
        int id = view.getId();
        switch (id){
            case R.id.id_btn_regist_receiver:
            {
                //定义过滤器
                IntentFilter filter = new IntentFilter();
                filter.addAction("luhuadeng");
                //创建MyBroadCastReceiver类的实例
                myReceiver = new MyBroadCastReceiver();
                //注册
                registerReceiver(myReceiver,filter);
                break;
            }
            case R.id.id_btn_send_broadcast:
            {
                //定义广播意图
                Intent intent = new Intent();
                intent.setAction("luhuadeng");//设置意图对应的动作
                intent.putExtra("progress",10);//在意图中添加参数

                //发送广播
                sendBroadcast(intent);
                break;
            }
            case R.id.id_btn_unregister_receiver:
            {
                unregisterReceiver(myReceiver);
                break;
            }
        }

    }

    class MyBroadCastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            int progress = intent.getIntExtra("progress",0);
            Log.e(TAG, "onReceive: "+progress );
        }
    }
}
